package com.xingda.packing.appset.impl;

import com.alibaba.fastjson.JSONObject;
import com.xingda.packing.appset.AppSetService;
import com.xingda.packing.config.appset.AppSetPLC;
import com.xingda.packing.config.appset.AppSetRule;
import com.xingda.packing.minitor.dto.PkBoxDetailInfoDto;
import com.xingda.packing.minitor.entity.PkTask;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

@Component
public class AppSetServiceImpl implements AppSetService {
    private final static String BOXRULES = "box_rules";
    private final static String BOXRULES_CODE_SHOW = "show";
    private final static String BOXRULES_CODE_SAVE = "save";
    private final static String BOXRULES_CODE_SAVE_PKTASK = "pkTask";

    private static JSONObject nodesJson = null;

    @Resource
    AppSetPLC appSetPlc;

    @Resource
    AppSetRule appSetRule;


    @Override
    public PkBoxDetailInfoDto getPkBoxDetailInfoDto(String code) {
        PkBoxDetailInfoDto pkBoxDetailInfoDto = null;
        JSONObject boxRulesJson = appSetRule.getJSONObject(BOXRULES);
        if (Objects.nonNull(boxRulesJson) && !boxRulesJson.isEmpty()) {
            JSONObject ruleJson = boxRulesJson.getJSONObject(code);
            if (Objects.nonNull(ruleJson) && !ruleJson.isEmpty()) {
                JSONObject showJson = ruleJson.getJSONObject(BOXRULES_CODE_SHOW);
                if (Objects.nonNull(showJson) && !showJson.isEmpty()) {
                    pkBoxDetailInfoDto = showJson.toJavaObject(PkBoxDetailInfoDto.class);
                }
            }
        }
        return pkBoxDetailInfoDto;
    }

    @Override
    public PkTask getTaskByCode(String code) {
        PkTask pkTask = null;
        JSONObject boxRulesJson = appSetRule.getJSONObject(BOXRULES);
        if (Objects.nonNull(boxRulesJson) && !boxRulesJson.isEmpty()) {
            JSONObject ruleJson = boxRulesJson.getJSONObject(code);
            if (Objects.nonNull(ruleJson) && !ruleJson.isEmpty()) {
                JSONObject saveJson = ruleJson.getJSONObject(BOXRULES_CODE_SAVE);
                if (Objects.nonNull(saveJson) && !saveJson.isEmpty()) {
                    JSONObject pkTaskJson = saveJson.getJSONObject(BOXRULES_CODE_SAVE_PKTASK);
                    if (Objects.nonNull(pkTaskJson) && !pkTaskJson.isEmpty()) {
                        pkTask = pkTaskJson.toJavaObject(PkTask.class);
                    }

                }
            }
        }
        return pkTask;
    }

    @Override
    public JSONObject getPlcNodes() {
        if (nodesJson == null) {
            nodesJson = appSetPlc.getJSONObject("plc").getJSONObject("nodes");
        }
        return nodesJson;
    }
}
